<?php

namespace App\Http\Controllers;

use App\Constant\Enum;
use App\Models\Transaction;
use App\Models\UserWithdraw;
use App\Services\Withdraw\UserWithdrawService;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class PaymentKylinController extends Controller
{
    public function transfer(Request $request)
    {
        Log::channel('transfer')->info(json_encode([
            'method' => $request->method(),
            'uri' => $request->path(),
            'ip' => $request->ip(),
            'body' => $request->all(),
        ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));

        DB::beginTransaction();
        try {
            $companyId = $request->post('companyId');
            $bizContent = $request->post('bizContent');
            if (!is_array($bizContent)) {
                $bizContent = (array)json_decode($bizContent, true);
            }
            if (empty($bizContent)) {
                throw new \Exception('bizContent 解析失败！');
            }
            $outBizNo = $bizContent['outBizNo'];
            $orderId = $bizContent['orderId'];

            /** @var Transaction $transaction */
            $transaction = Transaction::query()->where([
                'transaction_no' => $outBizNo,
                'remote_order_no' => $orderId,
            ])->first();
            if (empty($transaction)) {
                throw new \Exception('交易信息不存在!');
            }
            /** @var UserWithdraw $userWithdraw */
            $userWithdraw = UserWithdraw::query()->findOrFail($transaction->getAttribute('user_withdraw_id'));
            if ($userWithdraw->getAttribute('status') != Enum::WITHDRAW_STATUS_APPROVED) {
                throw new \Exception('数据异常，转账未审核!');
            }

            $paymentStatus = $bizContent['paymentStatus'];
            if ($transaction->getAttribute('status') != Enum::TRANSACTION_STATUS_PENDING) {
                return response()->json([
                    'code' => 400,
                    'message' => '请求已处理！'
                ]);
            }
            if ($paymentStatus == 'SUCCESS') {
                $transaction->update([
                    'status' => Enum::TRANSACTION_STATUS_APPROVED,
                    'finished_at' => Carbon::now(),
                ]);

                UserWithdrawService::handleWalletWhenTransactionSuccess($userWithdraw);
            } else {
                $transaction->update([
                    'status' => Enum::TRANSACTION_STATUS_REJECT,
                    'finished_at' => Carbon::now(),
                ]);
                $userWithdraw->update([
                    'remark' => $userWithdraw->getAttribute('remark') . ' ###转账失败：' . $bizContent['failReason'],
                ]);

                UserWithdrawService::handleWalletWhenTransactionFailed($userWithdraw);
            }

            DB::commit();
            // 结束回调
            return response()->json([
                'code' => 200
            ]);
        } catch (\Exception $exception) {
            DB::rollBack();
            return response()->json([
                'code' => 500,
                'message' => $exception->getMessage(),
            ]);
        }
    }

    public function directTransfer(Request $request)
    {
        Log::channel('transfer')->info(json_encode([
            'method' => $request->method(),
            'uri' => $request->path(),
            'ip' => $request->ip(),
            'body' => $request->all(),
        ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));

        DB::beginTransaction();
        try {
            $outBizNo =  $request->post('outBizNo');
            $orderId =  $request->post('accTransNo');

            /** @var Transaction $transaction */
            $transaction = Transaction::query()->where([
                'transaction_no' => $outBizNo,
            ])->first();
            if (empty($transaction)) {
                throw new \Exception('交易信息不存在!');
            }
            /** @var UserWithdraw $userWithdraw */
            $userWithdraw = UserWithdraw::query()->findOrFail($transaction->getAttribute('user_withdraw_id'));
            if ($userWithdraw->getAttribute('status') != Enum::WITHDRAW_STATUS_APPROVED) {
                throw new \Exception('数据异常，转账未审核!');
            }

            $paymentStatus = strtolower($request->post('status'));
            if ($transaction->getAttribute('status') != Enum::TRANSACTION_STATUS_PENDING) {
                return 'failed';
            }
            if ($paymentStatus == 'success') {
                $transaction->update([
                    'status' => Enum::TRANSACTION_STATUS_APPROVED,
                    'remote_order_no' => $orderId,
                    'finished_at' => Carbon::now(),
                ]);

                UserWithdrawService::handleWalletWhenTransactionSuccess($userWithdraw);
            } else {
                $transaction->update([
                    'status' => Enum::TRANSACTION_STATUS_REJECT,
                    'finished_at' => Carbon::now(),
                ]);
                $userWithdraw->update([
                    'remark' => $userWithdraw->getAttribute('remark') . ' ###转账失败：' . $request->post('failReason'),
                ]);

                UserWithdrawService::handleWalletWhenTransactionFailed($userWithdraw);
            }

            DB::commit();
            // 结束回调
            return 'success';
        } catch (\Exception $exception) {
            DB::rollBack();
            return 'failed';
        }
    }


    public function invoke()
    {

    }
}
